package com.v2future.sjt.collegecheckingattendance.leave;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.v2future.sjt.collegecheckingattendance.MainActivity;
import com.v2future.sjt.collegecheckingattendance.R;
import com.v2future.sjt.collegecheckingattendance.home.HomeActivity;
import com.v2future.sjt.collegecheckingattendance.utils.BaseResponseBean;
import com.v2future.sjt.collegecheckingattendance.utils.Constants;
import com.v2future.sjt.collegecheckingattendance.utils.StringUtil;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.BaseRequestParams;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetTaskListener;
import com.v2future.sjt.collegecheckingattendance.utils.netutils.NetUtils;

import org.xutils.x;

import java.io.File;
import java.util.Collections;
import java.util.List;

import me.gujun.android.taggroup.TagGroup;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 外出假填写原因，上传凭证
 * @author shijianting
 * @time 2016/3/30 11:12
 */
public class OutLeaveFillinInfoActivity extends MainActivity implements View.OnClickListener{

    /**
     * 请假原因
     */
    private EditText contentEt;
    /**
     * 凭证图片
     */
    private ImageView evidenceIv;
    /**
     * 提交按钮
     */
    private Button submitBtn;

    /**
     * 日期栏
     */
    private TagGroup tg;

    /**
     * 选择的日期
     */
    private List<String> selectDates;

    /**
     * 凭证图片路径
     */
    private String evidencePath;

    int REQUEST_IMAGE = 1001;

    private boolean isShowAllTags = false;

    /**
     * init first
     */
    @Override
    public void init() {
        selectDates = (List<String>) getIntent().getSerializableExtra(OutLeaveDatePickerActivity.TAG_SELECT_DATE);
        //排序
        Collections.sort(selectDates);
    }

    /**
     * init view
     */
    @Override
    public void initView() {
        setContentView(R.layout.activity_outleave_fillin_info);
        initTitleBack(null);
        setTitleText("请外出假");
        contentEt = (EditText) findViewById(R.id.et_content);
        evidenceIv = (ImageView) findViewById(R.id.iv_evidence);
        evidenceIv.setOnClickListener(this);
        submitBtn = (Button) findViewById(R.id.btn_submit);
        submitBtn.setOnClickListener(this);
        tg = (TagGroup) findViewById(R.id.tg1);
        tg.setOnTagClickListener(new TagGroup.OnTagClickListener() {
            @Override
            public void onTagClick(String tag) {
                if (tag.equals("……")) {
                    initDateTags(true);
                }
            }
        });
    }

    /**
     * init after
     */
    @Override
    public void initAfter() {
        //一些数据判断
        if (selectDates == null || selectDates.size() == 0) {
            tip("请假日期有误");
            finish();
        }
        initDateTags(isShowAllTags);
    }

    /**
     * 日期tag
     * @param isShowAll 是否显示全部
     */
    private void initDateTags(boolean isShowAll){
        String[] dateTags = null;
        if (isShowAll) {
            dateTags = new String[selectDates.size()];
            for (int i=0;i<dateTags.length;i++) {
                dateTags[i] = selectDates.get(i);
            }
        }
        else {
            if (selectDates.size() > 5) {
                dateTags = new String[6];
            }
            else {
                dateTags = new String[selectDates.size()];
            }
            for (int i=0;i<dateTags.length;i++) {
                if (i >= 5) {
                    dateTags[i] = "……";
                    break;
                }
                else {
                    dateTags[i] = selectDates.get(i);
                }
            }
        }

        tg.setTags(dateTags);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_IMAGE){
            if(resultCode == RESULT_OK){
                // Get the result list of select image paths
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (path.size() > 0 ) {
                    x.image().bind(evidenceIv, path.get(0).toString(), getImageOptions(80, 80));
                    evidencePath = path.get(0).toString();
                }
            }
        }
    }

    /**
     * 请假请求
     */
    private void doSubmitLeave(){
        if (TextUtils.isEmpty(evidencePath)) {
            tip("请上传请假凭证");
            return;
        }
        showLoadingDialog();
        BaseRequestParams params = new BaseRequestParams(this, formatUrlDo(Constants.PUBLISH_EVENT));
        params.setMultipart(true);
        params.addQueryStringParameter("type", "2");//请假状态写死
        params.addQueryStringParameter("leaveType", "3");//外出假为3
        params.addQueryStringParameter("leaveReason", contentEt.getText().toString());
        params.addQueryStringParameter("termId", "1");
        params.addQueryStringParameter("leaveDate", StringUtil.formatStringList(selectDates));//请假日期
        params.addQueryStringParameter("imageName0", urlEncode(evidencePath));
        params.addBodyParameter("imageBody0", new File(evidencePath), null);
        NetUtils.doPostRequestWithFiles(this, params, new NetTaskListener<BaseResponseBean>() {

            @Override
            public void onSuccess(BaseResponseBean result) {
                tip("提交请假完成");
                Intent intent = new Intent(OutLeaveFillinInfoActivity.this, HomeActivity.class);
                gobackWithData(intent);
            }

            @Override
            public void onError() {

            }

            @Override
            public void onInterError(BaseResponseBean result) {
                tip(result.getFailReason());
            }

            @Override
            public void onNetError(int responseCode, String responseMsg, String errorResult) {
                tip(responseMsg);
            }

            @Override
            public void onCancelled() {

            }

            @Override
            public void onFinished() {
                cancelLoadingDialog();
            }

            @Override
            public void onSuccessCache(BaseResponseBean result) {

            }
        });
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /**
             * 凭证
             */
            case R.id.iv_evidence:
                Intent intent = new Intent(OutLeaveFillinInfoActivity.this, MultiImageSelectorActivity.class);
                // whether show camera
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                // max select image amount
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
                // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                // default select images (support array list)
//                intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultDataArray);
                startActivityForResult(intent, REQUEST_IMAGE);
                break;
            /**
             * 提交
             */
            case R.id.btn_submit:
                doSubmitLeave();
                break;
            case R.id.tg1:
                isShowAllTags = !isShowAllTags;
                initDateTags(isShowAllTags);
                break;
        }
    }
}
